package com.api.ld.web;

import com.engine.ld.functions.sap.cgxx.ZMM_PURCHASEINFODATA_IMPProxy;
import com.engine.ld.optimize.CgxxNew;
import com.engine.ld.utils.DealXml;
import com.weaver.general.BaseBean;
import weaver.conn.RecordSet;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.Map;

/**
 * @author ZhangLei
 * @date 2021/7/1
 */
public class CgxxAction implements Action {
    public static final BaseBean bb = new BaseBean();

    @Override
    public String execute(RequestInfo requestInfo) {
        bb.writeLog("step1----------------");
        return CgxxHandle(requestInfo.getRequestid(),requestInfo);
    }

    private String CgxxHandle(String requestid,RequestInfo requestInfo){
        String back = Action.FAILURE_AND_CONTINUE;
//        规范的XML字段
        bb.writeLog("step2----------------");


        try {
            bb.writeLog("step3----------------");
            ZMM_PURCHASEINFODATA_IMPProxy pp = new ZMM_PURCHASEINFODATA_IMPProxy();

            String SAPBackXml = pp.getZMM_PURCHASEINFODATA_IMP_PortType().ZMM_PURCHASEINFODATA_IMP(new CgxxNew().CgxxSelect(requestid,requestInfo));
            bb.writeLog("SAP的返回参数是："+SAPBackXml);
            bb.writeLog("step4----------------");
//            String SAPBackXml = pp.getZMM_PURCHASEINFODATA_IMP_PortType().ZMM_PURCHASEINFODATA_IMP(normXMl);
//            bb.writeLog("传给sap的xml参数是："+normXMl);
            bb.writeLog("step5----------------");
            Map<String, Object> sapBackMap = new DealXml().XmlResultMap(SAPBackXml);
            bb.writeLog("step6---"+sapBackMap);
            String type = sapBackMap.get("TYPE").toString();
            String message = sapBackMap.get("MESSAGE").toString();
            message = message.contains("'")?message.replace("'","''"):message;
            bb.writeLog("step7----------------");

            bb.writeLog("解析后，type:"+type+";message:"+message);
            boolean b = saptodatabase(type, message, requestid);

            bb.writeLog("SAP返回结果添加到数据库："+b);

            if ("S".equals(type)){
                back = Action.SUCCESS;
            }else {
                back = Action.FAILURE_AND_CONTINUE;
                bb.writeLog("SAP返回结果为E,错误信息为："+message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        bb.writeLog("返回的结果是："+back);
        return back;
    }


    /*将sap返回的结果存入数据库*/
    private boolean saptodatabase(String type, String message,String requestid){
        String sql = "UPDATE formtable_main_155 SET TYPE='"+type+"',MESSAGE='"+message+"' WHERE requestId="+requestid;
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(sql);
    }
}
